<?php
class AdminSpace_Controller extends AdminController {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        // Upcoming viSeminars
        $viSeminarList = $this->dao->queryAll(
                'SELECT * FROM vi_seminar WHERE end_date >= :end_date ORDER BY begin_date ASC, begin_time ASC LIMIT 8',
                array('end_date' => sql::$TODAY));
        $this->viewData['upcomingViSeminarList'] = $viSeminarList;
        foreach ($this->viewData['upcomingViSeminarList'] as &$viSeminar) {
            $viSeminar['registrationCount'] = $this->dao->registrationCountOfViSeminar($viSeminar['id']);
        }

        // Recent viSeminars (useful for accounting)
        $viSeminarList = $this->dao->queryAll(
                'SELECT * FROM vi_seminar WHERE end_date < :end_date ORDER BY begin_date DESC, begin_time DESC LIMIT 3',
                array('end_date' => sql::$TODAY));
        $this->viewData['recentViSeminarList'] = $viSeminarList;
        foreach ($this->viewData['recentViSeminarList'] as &$viSeminar) {
            $viSeminar['registrationCount'] = $this->dao->registrationCountOfViSeminar($viSeminar['id']);
        }
        
        $this->renderSubview('admin/welcome');
    }

    public function quickSearchVi() {
        $viRegistrationId = $this->input->get('viRegistrationId');
        $this->viewData['viRegistrationId'] = $viRegistrationId;

        if (! valid::isId($viRegistrationId)) {
            $this->msg->error('error.invalidId');
            $this->renderSubview('/admin/welcome');
            return;
        }

        $viRegistration = $this->dao->getById('vi_registration', $viRegistrationId);
        if (! $viRegistration) {
            $this->msg->error('admin.viRegistrationNotFound', $viRegistrationId);
            $this->renderSubview('/admin/welcome');
            return;
        }

        $this->redirect('/admin/viRegistration/display?id=' . $viRegistrationId);
    }

    public function entityInfo() {
        $pkField = $this->input->get('pkField');
        $pkValue = $this->input->get('pkValue');
        $entityName = $this->input->get('entityName');
        if (valid::isEmpty($entityName) || valid::isEmpty($pkField) || valid::isEmpty($pkValue)) {
            return;
        }

        try {
            $entity = $this->dao->getUnique($entityName, array($pkField => $pkValue));
            $entity = $this->dao->fetchCreatedAndModified($entity);
            $this->viewData['entity'] = $entity;
            $this->viewData['displayInMainWindowIcon'] = FALSE;
            $this->renderSubview('/admin/entityInfo');
        }
        catch (Exception $e) {
            // Be quiet, this is probably an attack :-)
            Kohana::log('alert', 'Attempt to create an invalid query: ' . $e);
            echo html::img('error.png');
            return;
        }
    }
}